import { Notify, Dialog } from 'quasar'

export interface ResponseData {
  code: number,
  msg: string,
  data: unknown,
}

export interface Request {
  url: string,
  data: string,

  setRequestHeader (key: string, value: string): void,
}

/** @mixin iDefaultOptions */
const defaultOptions = {
  // Token 通过 Header 携带
  // beforeSend: (req: Request) => {
  //   if (typeof localStorage !== 'undefined') {
  //     const token = localStorage.getItem('x-access-token')
  //     if (token) {
  //       req.setRequestHeader('x-access-token', token)
  //     }
  //   }
  // },
  errCallback (msg: string) {
    console.error(msg)
    Notify.create({
      message: msg,
      color: 'red',
      icon: 'announcement',
      position: 'top'
    })
  },
  successHandler (res: ResponseData) {
    if (res.code === 2) {
      Dialog.create({
        title: '数据权限异常',
        message: '检测尝试请求当前账号权限之外的数据，是否切换登录角色',
        cancel: true,
        persistent: true,
        color: 'red'
      }).onOk(() => {
        location.href = '/login'
      })
    }
    return {
      success: res.code === 0,
      data: res.data,
      msg: res.msg
    }
  },
  // [x] 不同参数的 GET 请求会被 merge
  // merge: true,
  baseURL: process.env.baseApi,
  withCredentials: true
}

export default defaultOptions
export { defaultOptions }
